package com.clinbrain;

import com.facebook.presto.spi.function.Description;
import com.facebook.presto.spi.function.ScalarFunction;
import com.facebook.presto.spi.function.SqlNullable;
import com.facebook.presto.spi.function.SqlType;
import com.facebook.presto.spi.type.StandardTypes;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 人名检测
 */
public final class NameDetection {


    private NameDetection() {

    }

    @ScalarFunction("name_detection")
    @Description("name_detection")
    @SqlNullable
    @SqlType("varchar")
    public static Slice nameDetection(@SqlType(StandardTypes.VARCHAR) Slice nameDisplaySli,
                                      @SqlType(StandardTypes.VARCHAR) Slice familyNameSli,
                                      @SqlType(StandardTypes.VARCHAR) Slice firstNameSli) {

        if (null == nameDisplaySli || 0 == nameDisplaySli.length()) {
            return null;
        }

        if (null == familyNameSli || 0 == familyNameSli.length()) {
            return null;
        }
        if (null == firstNameSli || 0 == firstNameSli.length()) {
            return null;
        }

        String nameDisplay = nameDisplaySli.toStringUtf8().trim();
        String familyName = familyNameSli.toStringUtf8().trim();
        String firstName = firstNameSli.toStringUtf8().trim();

        // 中文
        if (isChinese(nameDisplay)) {
            return nameDisplaySli;
        } else {
            // 判断是否包含 '.'
            if (familyName.contains(".")) {
                if (familyName.length() <= 2) {
                    return null;
                }
            }

            if (firstName.contains(".")) {
                if (firstName.length() <= 2) {
                    return null;
                }
            }
            return Slices.utf8Slice(nameDisplay.replace(", ",","));
        }

    }

    private static Pattern pattern;

    static {
        String regex = "[\u4e00-\u9fa5]";
        pattern = Pattern.compile(regex);
    }


    public static boolean isChinese(String nameDisplay) {
        Matcher matcher = pattern.matcher(nameDisplay);
        return matcher.find();
    }

    public static void main(String[] args) {
        Slice nameDisplaySli = Slices.utf8Slice("xia,hu");
        Slice familyNameSli = Slices.utf8Slice("x.h");
        Slice firstNameSli = Slices.utf8Slice(".u");
        System.out.println(nameDetection(nameDisplaySli, familyNameSli, firstNameSli));
    }
}
